<?php
session_start();
include_once(LIB_PATH . 'query.php');
        
# USER VARIABLES
$userId = isset($_SESSION['id']) ? $_SESSION['id']   : die('ERROR 403: FORBIDDEN'); 
$user   = new QUERY(array('TABLE'=>'member','KEY'=>array('member_id'=>$userId),'COLS'=>array('photo'))); 


# THE POST_ID WHERE COMMENT (AND ALL OTHER ACTIONS) ARE BEING DONE
$postId = isset($_POST['postId']) ? $_POST['postId'] : false;


# WHEN A COMMENT WAS SUBMITTED
$comment = isset($_POST['comment']) ? urldecode($_POST['comment']) : false; 

    
# WHEN USER DELETES A COMMENT
 $deleteId = isset($_POST['delete']) ? $_POST['delete'] : false;    


?>
    <img src='<?=USER_THUMB.$user->fetch('photo')?>' class='tinyPhoto' />
    <textarea name='txtComment<?=$postId?>' id='txtComment<?=$postId?>' placeholder='Type your comment...' class='animated'></textarea>
    <input type='button' name='btnComment' id='btnComment' class='btnComment' value='comment' onclick='submitComment("<?=$postId?>");' />
    <div id='divLoading<?=$postId?>' class='divLoading'></div>

<?php
  
# ADD NEW COMMENT
 if($postId && $comment)
     {
       $newComment = new QUERY(array('TABLE'=>'comments'));
       
       $data = array('post_id'       => $postId,
                     'comment'       => $comment,
                     'commented_as'  => 'USER',
                     'comment_as_id' => $userId,
                     'commented_on'  => date('Y-m-d h:i:s')
                    );
       $newComment->save($data);        
     }
     
 # DELETE A COMMENT
   if($postId && $deleteId)
    {
       
       $commentDel = new QUERY(array('TABLE'=>'comments','KEY'=>array('comment_id'=>$deleteId)));
       $commentDel->delete();
    }  
     
 # PREPARE THE CONDITIONS 
   $key = array('post_id'=>$postId);  
 
 # CREATE THE QUERY  
   $comment = new QUERY(array('TABLE'=>'comments','KEY'=>$key,'DESC'=>'commented_on'));
    
 # FETCH ALL COMMENTS
    $results = $comment->fetchAll();
      
   if($results)
       {
         $ctr=0;
         echo'<ul class="comment">';
         foreach($results as $row)
            {
              $key = array('member_id'=>$row['comment_as_id']);
              $cols = array('name'=>'first_name," ",last_name','photo'); 
              
              $user = new QUERY(array('TABLE'=>'member','KEY'=>$key,'COLS'=>$cols));
             
              $className = ($ctr%2==0)?'BGDark':'BGLight';
              
              echo'<li class="commentContainer '.$className.'">';
              echo'<img src="'.USER_THUMB.$user->fetch('photo').'" class="tinyPhoto">';
              echo'<span class="commentName">'.$user->fetch('name'). '</span> <span class="commentSay">said:</span>'.'<br />';
              echo'<span class="commentBody">' . $row['comment'] . '</span><br />';
              echo'<span class="date commentDate">'.$this->date->format($row['commented_on']).'</span>';
              
              echo $userId==$row['comment_as_id'] ? '<span class="commentDelete" onclick="deleteComment('.$postId.','.$row['comment_id'].')">delete</span>':'';
              echo'</li>';
              $ctr++;
            } // 
         echo'</ul>' ;
       }
    else
       {
           echo '<p class="commentNone">No comment found</p>';    
       }
?>
<script type='text/javascript' src='<?=JS_PLUG.'jquery.autosize.min.js'?>'></script>    
<script>
     
$(document).ready(function(){
       
      
      
       $(function(){
            $('.normal').autosize();
            $('.animated').autosize({append: "\n"});
       });
       
       
        // FUNCTION FOR PRESSING THE ENTER KEY ON TEXTBOX   
        (function($){ 
            $.fn.onEnter = function(func){
                this.bind('keypress',function(e){
                    if(e.keyCode === 13) func.apply(this, [e]);
                });
                return this;
            }
        })(jQuery);

        // ON BUTTON CLICK            
                     /*

        $('#btnComment').click(function(){
           var postId  = 
               alert('PostID: ' + postId);             
                    $.ajax({
                        type: 'POST',
                        url : '../ajax/ir_comments',
                        data: { 
                               postId : postId,
                               comment:encodeURIComponent($('#txtComment').val())
                              },
                        success : function(res)
                        {
                          var container = $('#divComment'+postId);
                              container.html(res);
                        }
                    }); // 
        }); */
        
      
        
        // ON ENTER 
        /*
        $('#txtComment').onEnter(function(){
             var postId  = 
             
                    $.ajax({
                        type: 'POST',
                        url : '../ajax/ir_comments',
                        data: { 
                               postId : postId,
                               comment:encodeURIComponent($(this).val())
                              },
                        success : function(res)
                        {
                          var container = $('#divComment'+postId);
                              container.html(res);
                        }
                    });  
          });
          */
          
    
});
// ON BUTTON SUBMIT
  function submitComment(postId)
        {
            
        var content   = $('#txtComment'+postId);
        var container = $('#divComment'+postId);
        var loader    = $('#divLoading'+postId);
        
            $.ajax({
                        type: 'POST',
                        url : '../ajax/ir_comments',
                        data: { 
                               postId : postId,
                               comment:encodeURIComponent(content.val())
                              },
                          
                        beforeSend: function()
                        {
                          loader.html('<img src="../../../assets/images/system/loading.gif">');
                        },
                               
                        success : function(res)
                        {
                          loader.html(null);  
                          container.html(res);
                        }
                    }); 
        }


// ON DELETE
          function deleteComment(postId,commentId){
           
        
             var loader    = $('#divLoading'+postId);
        
          
              if(confirm('Delete your comment?'))
              {
                  $.ajax({
                        type: 'POST',
                        url : '../ajax/ir_comments',
                        data: { 
                               postId : postId,
                               delete : commentId
                              },
                        beforeSend: function()
                        {
                          loader.html('<img src="../../../assets/images/system/loading.gif">');
                        },
                          
                        success : function(res)
                        {
                          var container = $('#divComment'+postId);
                              container.html(res);
                        }
                    });
              } 
          }
       
</script>